import axios from 'axios'
import { ElMessage, ElLoading } from 'element-plus'

// import { useRouter } from 'vue-router'
// const router = useRouter()
// router
let loading = false
// setTimeout(() => {
//   loading.close()
// }, 2000)
let url = 'http://106.52.180.164:1080'
const http = axios.create({
  // baseURL: 'http://8.134.118.190:19900',
  // baseURL: 'http://192.168.189.66:19900',
  // eslint-disable-next-line no-undef
  // baseURL: process.env.NODE_ENV === 'production' ? BASE_URL : process.env.VUE_APP_DEV_BASE_URL,
  baseURL: url,
  timeout: 5000,
})

// request interceptor
http.interceptors.request.use(
  (config) => {
    console.log(
      'method:' + config.method + ', url:' + config.url + ', data:' + JSON.stringify(config.data)
    )
    if (config.method === 'post' || config.method === 'put') {
      loading = ElLoading.service({
        lock: true,
        text: 'Loading',
        spinner: 'el-icon-loading',
        background: 'rgba(0, 0, 0, 0.7)',
      })
    }

    return config
  },
  (error) => {
    // do something with request error
    console.log('http req err', error) // for debug
    // log.error(error)
    return Promise.reject(error)
  }
)

// response interceptor
http.interceptors.response.use(
  /**
   * If you want to get http information such as headers or status
   * Please return  response => response
   */

  /**
   * Determine the request status by custom code
   * Here is just an example
   * You can also judge the status by HTTP Status Code
   */
  (response) => {
    if (loading) {
      loading.close()
    }
    //
    const res = response.data
    // debugger
    if (response.config.method == 'post') {
      if (res.showMessage) {
        ElMessage({
          message: res.message || '提交成功',
          type: 'success',
        })
      }
    } else if (response.config.method == 'put') {
      if (res.showMessage) {
        ElMessage({
          message: res.message || '修改成功',
          type: 'success',
        })
      }
    }

    return res
  },
  (error) => {
    // log.error(error)
    if (loading) {
      loading.close()
    }
    console.log('http res err' + error) // for debug
    // ElMessage({
    //   message: '请求超时',
    //   type: 'error',
    // })
    // MessageBox({ msg: '等待服务器启动完成' })
    // return Promise.reject(error)
    return Promise.reject(error)
  }
)

export default http
